package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhentao.mapper.AdUserMapper;
import com.zhentao.model.admin.domain.AdUser;
import com.zhentao.model.admin.dto.AdUserDto;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.service.AdUserService;
import com.zhentao.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl implements AdUserService {
    @Autowired
    private AdUserMapper adUserMapper;
    @Override
    public ResponseResult login(AdUserDto dto) {
        if(StringUtils.isNotBlank(dto.getName()) || StringUtils.isNotBlank(dto.getPassword())){
            AdUser adUser = adUserMapper.selectOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
            if(adUser == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            String salt = adUser.getSalt();
            String newPassword = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
            if( !adUser.getPassword().equals(newPassword)){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            Map<String , Object> map =new HashMap<>();
            String token = AppJwtUtil.getToken(adUser.getId().longValue());
            adUser.setPassword(null);
            adUser.setSalt(null);
            map.put("token", token);
            map.put("user", adUser);
            return ResponseResult.okResult(map);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }
}
